// index.js
const { getTopLikedArticles } = require('../../utils/articles-data');
const DictionaryAPI = require('../../utils/dictionary-api');
const YoudaoAPI = require('../../utils/youdao-api');

Page({
  data: {
    searchKeyword: '',
    articles: [],
    isSearching: false
  },

  onLoad: function() {
    this.loadTopArticles();
  },

  onShow: function() {
    this.loadTopArticles();
  },

  // 加载点赞数前三的文章
  loadTopArticles: function() {
    // 获取点赞数前三的文章
    const topArticles = getTopLikedArticles(3);
    
    this.setData({
      articles: topArticles
    });
  },

  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 搜索单词
  searchWord: function() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入要查询的内容',
        icon: 'none'
      });
      return;
    }

    if (this.data.isSearching) {
      return; // 防止重复搜索
    }

    this.setData({ isSearching: true });

    wx.showLoading({
      title: '查询中...'
    });

    // 实例化API
    const dictionaryAPI = new DictionaryAPI();
    const youdaoAPI = new YoudaoAPI();

    // 检测语言类型
    const isChineseInput = this.detectChinese(keyword);

    if (isChineseInput) {
      // 中文输入：只使用有道翻译
      youdaoAPI.translateText(keyword).then(translationResult => {
        const wordData = {
          word: translationResult.translated,
          originalInput: keyword,
          chineseTranslation: keyword,
          englishTranslation: translationResult.translated,
          isFromChinese: true,
          phonetic: '',
          audioUrl: '',
          meanings: [{
            partOfSpeech: '',
            definition: translationResult.translated,
            example: ''
          }],
          etymology: [],
          synonyms: [],
          antonyms: [],
          memoryTip: ''
        };
        
        this.navigateToWordDetail(wordData);
      }).catch(error => {
        console.error('翻译失败:', error);
        wx.showToast({
          title: '翻译失败，请重试',
          icon: 'none'
        });
      }).finally(() => {
        wx.hideLoading();
        this.setData({ isSearching: false });
      });
    } else {
      // 英文输入：先翻译，再查词典获取详细信息
      Promise.all([
        youdaoAPI.translateText(keyword),
        dictionaryAPI.searchWord(keyword)
      ]).then(([translationResult, wordData]) => {
        // 翻译所有释义
        return youdaoAPI.translateMeanings(wordData.meanings).then(translatedMeanings => {
          // 合并翻译结果和词典数据
          const combinedWordData = {
            ...wordData,
            chineseTranslation: translationResult.translated,
            originalInput: keyword,
            isFromChinese: false,
            // 使用翻译后的释义并转换词性为简写形式
            meanings: translatedMeanings.map(meaning => ({
              ...meaning,
              partOfSpeech: this.convertPartOfSpeech(meaning.partOfSpeech)
            }))
          };
          
          return combinedWordData;
        });
      }).then(combinedWordData => {
        this.navigateToWordDetail(combinedWordData);
      }).catch(error => {
        console.error('查询失败:', error);
        // 如果词典查询失败，至少提供翻译结果
        youdaoAPI.translateText(keyword).then(translationResult => {
          const fallbackWordData = {
            word: keyword,
            originalInput: keyword,
            chineseTranslation: translationResult.translated,
            englishTranslation: keyword,
            isFromChinese: false,
            phonetic: '',
            audioUrl: '',
            meanings: [{
              partOfSpeech: '',
              definition: translationResult.translated,
              example: ''
            }],
            etymology: [],
            synonyms: [],
            antonyms: [],
            memoryTip: ''
          };
          
          this.navigateToWordDetail(fallbackWordData);
        }).catch(fallbackError => {
          console.error('翻译也失败了:', fallbackError);
          wx.showToast({
            title: '查询失败，请重试',
            icon: 'none'
          });
        });
      }).finally(() => {
        wx.hideLoading();
        this.setData({ isSearching: false });
      });
    }
  },

  // 检测是否为中文输入
  detectChinese: function(text) {
    const chineseRegex = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/;
    return chineseRegex.test(text);
  },

  // 转换词性为简写形式
  convertPartOfSpeech: function(partOfSpeech) {
    const conversions = {
      'noun': 'n.',
      'verb': 'v.',
      'adjective': 'adj.',
      'adverb': 'adv.',
      'pronoun': 'pron.',
      'preposition': 'prep.',
      'conjunction': 'conj.',
      'interjection': 'interj.',
      'article': 'art.',
      'determiner': 'det.',
      'numeral': 'num.',
      'auxiliary verb': 'aux.',
      'modal verb': 'modal',
      'phrasal verb': 'phr.v.',
      'gerund': 'ger.',
      'participle': 'part.',
      'infinitive': 'inf.'
    };
    
    return conversions[partOfSpeech.toLowerCase()] || partOfSpeech;
  },

  // 跳转到单词详情页面
  navigateToWordDetail: function(wordData) {
    // 将数据存储到全局，供word-detail页面使用
    const app = getApp();
    app.globalData.searchWordData = wordData;
    
    wx.navigateTo({
      url: `/pages/word-detail/word-detail?word=${wordData.word}&fromSearch=true`
    });
  },

  // 跳转到翻译页面
  goToTranslation: function() {
    wx.navigateTo({
      url: '/pages/translation/translation'
    })
  },

  // 跳转到背单词页面
  goToVocabulary: function() {
    wx.navigateTo({
      url: '/pages/vocabulary/vocabulary'
    })
  },





  // 跳转到文章详情页面
  goToArticle: function(e) {
    const articleId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    })
  }
})
